//
//  ProjectsTableViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 15/12/31.
//  Copyright © 2015年 李萍. All rights reserved.
//

import UIKit
import Foundation
import Alamofire
import SwiftyJSON
import Kingfisher
import ThPullRefresh

class ProjectsTableViewController: UITableViewController {
    
    var projects = [GTProject]()
    
    var projectsID: NSInteger = 0
    var userID: NSInteger = 0
    var languageID: NSInteger = 0
    var privateToken: String!
    
    var searchQuery: String = ""
    
    var projectsType: Int = 0
    var strUrl: String = ""
    var page: Int = 1
    var isHeadRefresh: Bool
    
    var projectCell: ProjectCell!
    
    init(projectType: Int) {
        self.isHeadRefresh = true
        self.projectsType = projectType

        super.init(nibName: nil, bundle: nil)
    }
    
    init(userID: NSInteger, projectType: Int) {
        self.isHeadRefresh = true
        self.userID = userID
        self.projectsType = projectType
        
        super.init(nibName: nil, bundle: nil)
    }
    
    init(privateToken: String) {
        self.isHeadRefresh = true
        self.privateToken = privateToken
        self.projectsType = 9
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.registerNib(UINib(nibName: "ProjectCell", bundle: nil), forCellReuseIdentifier: "projectCell")
        projectCell = self.tableView.dequeueReusableCellWithIdentifier("projectCell") as! ProjectCell
        
        page = 1
        self.fetchForProject()
        
        self.tableView.tableFooterView = UIView()
        self.tableView.addHeadRefresh(self) { () -> () in
            
            self.isHeadRefresh = true
            self.page = 1
            self.fetchForProject()
        }
        self.tableView.addFootRefresh(self) { () -> () in
            
            self.isHeadRefresh = false
            ++self.page
            self.fetchForProject()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //实现列表
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let projectCell = tableView.dequeueReusableCellWithIdentifier("projectCell", forIndexPath: indexPath) as? ProjectCell
    
        if indexPath.row < projects.count {
            let project = projects[indexPath.row]
            let url:NSURL = NSURL(string: "https://git.oschina.net/"+(project.owner?.portrait)!)!
            
            projectCell!.userPortraitImageView.kf_setImageWithURL(url, placeholderImage:UIImage.init(named: "portrait_loading"))
            projectCell!.nameLabel.text = "\(JSON((project.owner?.name)!))/"+"\(JSON(project.name!))"
            
            let string : String = "\(JSON(project.projectDescription!))"
            if string.isEmpty {
                projectCell!.contentLabel.text = "暂无项目介绍"
            } else {
                projectCell!.contentLabel.text = string
            }
            projectCell!.detailLabel.attributedText = project.detailForProjectLanguage()

            
        }
        
        
        return projectCell!
        
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if projects.count > 0 {
            return projects.count
        }
        return 0
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row < projects.count {
            let project = projects[indexPath.row]
            let string : String = "\(JSON(project.projectDescription!))"
            if string.isEmpty {
                projectCell!.contentLabel.text = "暂无项目介绍"
            } else {
                projectCell!.contentLabel.text = string
            }
            let height = projectCell.contentLabel.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
            
            return 75 + height
        }
        return 90
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.tableView!.deselectRowAtIndexPath(indexPath, animated: true)
        
        let projectDetailVC = ProjectDetailViewController(projectID: projects[indexPath.row].projectID!, namespace: projects[indexPath.row].nameSpace!)
        projectDetailVC.title = projects[indexPath.row].name

        projectDetailVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(projectDetailVC, animated: true)
    }
    
    //接口转换
    func stringWithUrl() -> String {
        strUrl = "https://git.oschina.net/api/v3/"
        switch projectsType {
        case 1:
            strUrl += "projects/featured?"
        case 2:
            strUrl += "projects/popular?"
        case 3:
            strUrl += "projects/latest?"
        case 4:
            strUrl += "events/user/"+"\(userID)"+"?"
        case 5:
            strUrl += "user/"+"\(userID)"+"/stared_projects?"
        case 6:
            strUrl += "user/"+"\(userID)"+"/watched_projects?"
        case 7:
            strUrl += "projects/languages/"+"\(languageID)"+"?"
        case 8:
            strUrl += "projects/search/"+"\(searchQuery)"+"?private_token="+"\(privateToken)"+"&"
        case 9:
            if (privateToken != nil) {
                strUrl += "projects?private_token="+"\(privateToken)"+"&"
            } else {
                strUrl += "user/+\(userID)+/projects?"
            }
            
        default:
            break
        }
        
        let string = strUrl+"page="+"\(page)"
        
        return string
    }
    //获取数据
    func fetchForProject() -> Void {
       
        Alamofire.Manager.sharedInstance.request(Method.GET, self.stringWithUrl()).responseJSON { response in
            if let results = response.result.value {
                if self.isHeadRefresh {
                    self.projects.removeAll(keepCapacity: Bool())
                }
                
                var jsonArray = JSON(results).array!
                
                for i in 0 ..< jsonArray.count {

                    let project = GTProject(json: jsonArray[i])

                    self.projects.append(project)
                }
                
                self.tableView.reloadData()
                self.tableView.tableHeadStopRefreshing()
                self.tableView.tableFootStopRefreshing()
            }
        }
    }
}

